﻿using System;
using System.Diagnostics;
using Simp.Model.CoreExpressions;

namespace Simp.Model
{
	/// <summary>Expression binding a parameter name with its value (both pass as parameters).</summary>
	/// <remarks>There is one main usage for this expression:  passing parameters to an expression.</remarks>
	[ExpressionName("ParameterBinding")]
	[ParameterPolicy("name", "value")]
	[DebuggerDisplay("{ExpressionHelper.Serialize(this)}")]
	public class ParameterBindingExpression : IExpression, IExpressionSerializer
	{
		/// <summary>Returns the corresponding parameter binding.</summary>
		/// <param name="parameters"></param>
		/// <returns></returns>
		public IParameterBinding GetParameterBinding(IExpression[] parameters)
		{
			if (parameters == null)
			{
				throw new ArgumentNullException("parameters");
			}
			if (parameters.Length != 2)
			{
				throw new ArgumentException("Should be exactly two parameters:  name and value", "parameters");
			}

			StringExpression name = parameters[0] as StringExpression;
			IExpression value = parameters[1];

			if (name == null)
			{
				throw new ArgumentException("First parameter should be a string", "parameters");
			}

			return ExpressionHelper.ParameterBindingFactory.Build(name.Value, value);
		}

		#region IExpressionSerializer Members
		void IExpressionSerializer.Serialize(AppendOnlyStringBuilder builder, params IExpression[] parameters)
		{
			if (builder == null)
			{
				throw new ArgumentNullException("builder");
			}
			if (parameters == null)
			{
				throw new ArgumentNullException("parameters");
			}
			if (parameters.Length != 2)
			{
				throw new ArgumentException("Should be exactly two parameters:  name and value", "parameters");
			}

			StringExpression name = parameters[0] as StringExpression;
			IExpression value = parameters[1];

			if (name == null)
			{
				ExpressionHelper.SerializeGeneric(builder, this, parameters);
			}
			else
			{
				builder.Append(name.Value);
				builder.Append(" = ");
				ExpressionHelper.Serialize(builder, value);
			}
		}
		#endregion
	}
}